package com.leaf.spring.y201911.day15;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;

/**
 * 自定义类加载器
 * 
 * @author gaowenjin
 *
 */
public class MyClassLoader extends ClassLoader {
	
	// 需要加载的类的classpath路径
	private String classpath;
	
	public MyClassLoader(String classpath) {
		// 指定父类加载器
		super(ClassLoader.getSystemClassLoader());
		this.classpath = classpath;
	}

	@Override
	protected Class<?> findClass(String name) throws ClassNotFoundException {

		byte[] b = loadClassData(name);

		// 将byte[]数组转换为类实例
		return defineClass(name, b, 0, b.length);
	}

	// 加载class类中的内容
	private byte[] loadClassData(String name) {

		try {
			
			name = name.replace('.', '/');

			FileInputStream input = new FileInputStream(new File(name));

			ByteArrayOutputStream output = new ByteArrayOutputStream();

			int b = 0;
			while ((b = input.read()) != -1) {
				output.write(b);
			}
			
			input.close();
			
			return output.toByteArray();

		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

}
